package com.als.healthymananger.service.impl;

import com.als.healthymananger.entity.Token;
import com.als.healthymananger.entity.User;
import com.als.healthymananger.service.LoginService;
import com.als.healthymananger.service.TokenService;
import com.als.healthymananger.service.UsersService;
import com.als.healthymananger.utils.Encoder;
import com.als.healthymananger.utils.JWTUtil;
import com.als.healthymananger.utils.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private Encoder encoder;
    @Autowired
    private UsersService usersService;
    @Autowired
    private JWTUtil jwtUtil;
    @Autowired
    private TokenService tokenService;
    private boolean flag;

    @Override
    public boolean validate(String username, String password) {
        boolean flag = true;

        // 空白字符匹配
        Pattern pblank = Pattern.compile("//s");

        // 全数字、字母匹配
        Pattern pps = Pattern.compile("\\w{6,26}");


        if (pblank.matcher(username).find())
            flag = false;
        if (pblank.matcher(password).find())
            flag = false;
        if (!pps.matcher(password).matches())
            flag = false;

        return flag;
    }

    @Override
    public User createUser(String username, String password, String userType) {
        User user = new User();
        user.setUsername(username);
        user.setType(userType);
        user.setPassword(encoder.encode(password));

        User u = null;
        try {
            if (usersService.save(user))
                u = usersService.getById(username);
                // 密码换为******
                u.setPassword("******");
                log.info("注册成功");
        } catch (Exception e) {
            log.error("exception: {}", e.getMessage());
            u = null;
        }
        return u;
    }

    @Override
    public String createJWT(String username, String type) {
        return jwtUtil.creteToken(username, type);
    }

    @Override
    public boolean loginExpired(Token token) {
        boolean flag = false;

        // 判断jwt是否过期
        if (jwtUtil.isExpired(token.getJwt()))
            flag = true;

        // 如果过期，删除token
        if (flag)
            tokenService.removeById(token.getId());

        return flag;

    }
}
